package com.lxw.station.service;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URL;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class RestTemplateService {

    public static final RestTemplate restTemplate = new RestTemplate();

    static {
//        Logger logger = (Logger) LoggerFactory.getLogger("ROOT");
//        logger.setLevel(Level.DEBUG);
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    public static String exchange(String url, HttpMethod method) {
        return exchange(url, method, null, null);
    }

    public static String exchange(String urlOrCurl, HttpMethod method, Object body) {
        HttpHeaders headers = null;
        if (urlOrCurl.startsWith("curl")) {
            headers = getHttpHeaders(urlOrCurl);
            urlOrCurl = getUrl(urlOrCurl);
        }
        return exchange(urlOrCurl, method, body, headers);
    }

    public static String exchange(String url, HttpMethod method, Object body, MultiValueMap<String, String> headers) {
        HttpHeaders tempHeaders = new HttpHeaders();
        if (headers != null) {
            tempHeaders.putAll(headers);
        }
        return exchange(url, method, body, tempHeaders);
    }

    public static String exchange(String url, HttpMethod method, HttpHeaders headers) {
        return exchange(url,method,null,headers);
    }
    public static String exchange(String url, HttpMethod method, Object body, HttpHeaders headers) {
        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, method, entity, String.class);
//        log.info(JSON.toJSONString(exchange));
        HttpStatus statusCode = exchange.getStatusCode();
        if (HttpStatus.OK.equals(statusCode)) {
            return exchange.getBody();
        } else {
            System.out.println("请求失败:" + url);
            System.out.println(exchange);
        }
        return "";
    }

    public static HttpHeaders getHttpHeaders(String bashCURL){
        HttpHeaders headers = new HttpHeaders();
        String[] hs = bashCURL.split("\n");
        for (int i = 0; i < hs.length; i++) {
            String h = hs[i];
            if (h.trim().startsWith("-H")) {
                h = h.replace("-H", "").replace("\\", "").replace("'","");
                headers.add(h.substring(0,h.indexOf(":")).trim(),h.substring(h.indexOf(":")+1).trim());
            }
        }
        return headers;
    }
    @SneakyThrows
    public static String getUrl(String bashCURL){
        String[] hs = bashCURL.split("\n");
        String curl = hs[0].replace("curl", "").replace("'", "").replace("\\", "").trim();
        URL tmp = new URL(curl);
        int port = tmp.getPort();
        String url = tmp.getProtocol()+"://";
        url = url+tmp.getHost();
        if (port!= -1) {
            url = url +":"+port;
        }
        url = url+tmp.getPath();
        return url;
    }

    public static void main(String[] args) {
        String curl = "curl 'https://blog.csdn.net/phoenix/web/v2/rank?page=2&pageSize=25&rankType=total_author' \\\n" +
                "  -H 'Accept: application/json, text/plain, */*' \\\n" +
                "  -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \\\n" +
                "  -H 'Connection: keep-alive' \\\n" +
                "  -H 'Referer: https://blog.csdn.net/rank/list/total' \\\n" +
                "  -H 'Sec-Fetch-Dest: empty' \\\n" +
                "  -H 'Sec-Fetch-Mode: cors' \\\n" +
                "  -H 'Sec-Fetch-Site: same-origin' \\\n" +
                "  -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36' \\\n" +
                "  -H 'sec-ch-ua: \"Google Chrome\";v=\"123\", \"Not:A-Brand\";v=\"8\", \"Chromium\";v=\"123\"' \\\n" +
                "  -H 'sec-ch-ua-mobile: ?0' \\\n" +
                "  -H 'sec-ch-ua-platform: \"Windows\"'";
        String[] hs = curl.split("\n");
        System.out.println(hs[0].replace("curl", "").replace("'","").replace("\\","").trim());
    }


}
